package com.raptor.trustworthy.task.config;

import java.nio.charset.StandardCharsets;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.client.RestTemplate;

/**
 * 定时任务配置
 *
 * @Author renhuan
 * @Date 2021-03-27 15:20
 **/
@Configuration
public class SchedulerConfig {

  /**
   *
   *
   * 声明定时任务工厂bean
   *
   * @return SchedulerFactoryBean    返回类型
   */
  private JobFactory jobFactory;

  public SchedulerConfig(JobFactory jobFactory){
    this.jobFactory = jobFactory;
  }

  /**
   * 配置SchedulerFactoryBean
   * 将一个方法产生为Bean并交给Spring容器管理
   * @return
   */
  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() {
    // Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    // 设置自定义Job Factory，用于Spring管理Job bean
    factory.setJobFactory(jobFactory);
    return factory;
  }

  @Bean(name = "scheduler")
  public Scheduler scheduler() {
    return schedulerFactoryBean().getScheduler();
  }



    @Bean
  public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate((factory));
    restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    return restTemplate;
  }

  @Bean
  public ClientHttpRequestFactory clientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(30000);
    factory.setConnectTimeout(30000);
    return factory;
  }


}